'use client';

import { useState, useEffect } from 'react';
import Sidebar from '@/components/Sidebar';

interface HistoryItem {
  url: string;
  title: string;
  timestamp: number;
  isFavorite: boolean;
  description?: string;
  order?: number;
  category?: string; // 添加分类ID字段
}

interface Category {
  id: string;
  name: string;
  color: string;
}

// 存储键常量
const STORAGE_KEYS = {
  HISTORY: 'videoHistory',
  CATEGORIES: 'videoCategories',
  API_INDEX: 'currentApiIndex',
  USERNAME: 'username'
};

// 默认分类
const DEFAULT_CATEGORIES: Category[] = [
  { id: 'movie', name: '电影', color: '#f43f5e' },
  { id: 'tv', name: '电视剧', color: '#3b82f6' },
  { id: 'variety', name: '综艺', color: '#10b981' },
  { id: 'anime', name: '动漫', color: '#f97316' },
  { id: 'education', name: '教育', color: '#8b5cf6' },
  { id: 'other', name: '其他', color: '#6b7280' }
];

const PARSE_APIS = [
  {
    name: '接口1',
    url: 'https://jx.xmflv.com/?url=',
  },
  {
    name: '接口2',
    url: 'https://jx.parwix.com:4433/player/?url=',
  },
  {
    name: '接口3',
    url: 'https://jx.iztyy.com/svip/?url=',
  },
  {
    name: '接口4',
    url: 'https://jx.bozrc.com:4433/player/?url=',
  },
  {
    name: '接口5',
    url: 'https://jx.4kdv.com/?url=',
  }
];

export default function Favorite() {
  const [history, setHistory] = useState<HistoryItem[]>([]);
  const [favorites, setFavorites] = useState<HistoryItem[]>([]);
  const [darkMode, setDarkMode] = useState(false);
  const [currentApiIndex, setCurrentApiIndex] = useState(0);
  const [searchTerm, setSearchTerm] = useState('');
  const [username, setUsername] = useState('用户');
  const [editingItem, setEditingItem] = useState<number | null>(null);
  const [tempTitle, setTempTitle] = useState('');
  const [editingDesc, setEditingDesc] = useState<number | null>(null);
  const [tempDescription, setTempDescription] = useState('');
  const [dragItemIndex, setDragItemIndex] = useState<number | null>(null);
  const [dragOverItemIndex, setDragOverItemIndex] = useState<number | null>(null);
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [categories, setCategories] = useState<Category[]>([]);
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
  const [editingCategoryIndex, setEditingCategoryIndex] = useState<number | null>(null);

  // 初始化主题和加载数据
  useEffect(() => {
    // 检查本地存储的主题设置
    const savedTheme = localStorage.getItem('theme');
    const prefersColorScheme = window.matchMedia('(prefers-color-scheme: dark)');
    const systemPrefersDark = prefersColorScheme.matches;
    
    // 根据保存的设置或系统偏好设置主题
    if (savedTheme === 'light') {
      // 用户明确设置为亮色
      setDarkMode(false);
      document.documentElement.classList.remove('dark');
    } else if (savedTheme === 'dark') {
      // 用户明确设置为暗色
      setDarkMode(true);
      document.documentElement.classList.add('dark');
    } else {
      // 没有保存过主题，根据系统偏好设置
      setDarkMode(systemPrefersDark);
      if (systemPrefersDark) {
        document.documentElement.classList.add('dark');
        localStorage.setItem('theme', 'dark');
      } else {
        document.documentElement.classList.remove('dark');
        localStorage.setItem('theme', 'light');
      }
    }
    
    // 监听主题变化事件（从其他页面触发的）
    const handleThemeChange = (e: CustomEvent) => {
      const newTheme = e.detail.theme;
      setDarkMode(newTheme === 'dark');
      if (newTheme === 'dark') {
        document.documentElement.classList.add('dark');
      } else {
        document.documentElement.classList.remove('dark');
      }
    };
    
    window.addEventListener('themeChange', handleThemeChange as EventListener);
    
    // 加载分类
    const savedCategories = localStorage.getItem(STORAGE_KEYS.CATEGORIES);
    if (savedCategories) {
      setCategories(JSON.parse(savedCategories));
    } else {
      // 如果没有保存的分类，使用默认分类
      setCategories(DEFAULT_CATEGORIES);
      localStorage.setItem(STORAGE_KEYS.CATEGORIES, JSON.stringify(DEFAULT_CATEGORIES));
    }
    
    // 加载历史记录
    const savedHistory = localStorage.getItem(STORAGE_KEYS.HISTORY);
    if (savedHistory) {
      const allHistory = JSON.parse(savedHistory) as HistoryItem[];
      
      // 筛选出收藏的项目
      const favItems = allHistory.filter(item => item.isFavorite);
      
      // 确保所有收藏项都有order属性
      let needsOrderUpdate = false;
      const updatedHistory = [...allHistory];
      
      // 先检查是否有任何收藏项缺少order属性
      const hasMissingOrder = favItems.some(item => item.order === undefined);
      
      // 如果有收藏项缺少order，重新为所有收藏项分配order
      if (hasMissingOrder) {
        // 获取已有的顺序（如果有）或按时间戳排序
        const sortedFavs = [...favItems].sort((a, b) => {
          if (a.order !== undefined && b.order !== undefined) {
            return a.order - b.order;
          }
          if (a.order !== undefined) return -1;
          if (b.order !== undefined) return 1;
          return b.timestamp - a.timestamp; // 越新的时间戳越大，放前面
        });
        
        // 为所有收藏项分配新的order
        sortedFavs.forEach((item, index) => {
          const historyIndex = updatedHistory.findIndex(h => h.timestamp === item.timestamp);
          if (historyIndex !== -1) {
            updatedHistory[historyIndex].order = index;
            needsOrderUpdate = true;
          }
        });
      }
      
      // 如果有更新，保存到localStorage
      if (needsOrderUpdate) {
        localStorage.setItem(STORAGE_KEYS.HISTORY, JSON.stringify(updatedHistory));
      }
      
      setHistory(updatedHistory);
      setFavorites(favItems);
    }

    // 加载当前接口索引
    const savedApiIndex = localStorage.getItem(STORAGE_KEYS.API_INDEX);
    if (savedApiIndex) {
      setCurrentApiIndex(parseInt(savedApiIndex, 10));
    }

    // 加载用户名
    const savedUsername = localStorage.getItem(STORAGE_KEYS.USERNAME);
    if (savedUsername) {
      setUsername(savedUsername);
    }
    
    return () => {
      window.removeEventListener('themeChange', handleThemeChange as EventListener);
    };
  }, []);

  const saveHistory = (newHistory: HistoryItem[]) => {
    setHistory(newHistory);
    localStorage.setItem(STORAGE_KEYS.HISTORY, JSON.stringify(newHistory));
    // 更新收藏列表
    setFavorites(newHistory.filter(item => item.isFavorite));
  };
  
  // 处理分类选择 - 保留但不再使用
  const handleSelectCategory = (categoryId: string | null) => {
    setSelectedCategory(categoryId);
  };
  
  // 更新收藏项的分类
  const updateItemCategory = (timestamp: number, categoryId: string | null) => {
    const newHistory = [...history];
    const index = newHistory.findIndex(item => item.timestamp === timestamp);
    if (index !== -1) {
      newHistory[index].category = categoryId || undefined;
      saveHistory(newHistory);
    }
    setEditingCategoryIndex(null);
  };

  const toggleFavorite = (favoriteItem: HistoryItem) => {
    const newHistory = [...history];
    const index = newHistory.findIndex(item => item.timestamp === favoriteItem.timestamp);
    if (index !== -1) {
      newHistory[index].isFavorite = !newHistory[index].isFavorite;
      saveHistory(newHistory);
    }
  };

  const removeFromHistory = (favoriteItem: HistoryItem) => {
    const newHistory = history.filter(item => item.timestamp !== favoriteItem.timestamp);
    saveHistory(newHistory);
  };

  // 处理URL，移除?后的所有参数
  const cleanUrl = (url: string) => {
    try {
      const urlObj = new URL(url);
      return urlObj.origin + urlObj.pathname;
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (error) {
      // 如果不是有效URL，直接返回原始值
      return url;
    }
  };

  const parseVideo = (url: string) => {
    // 清理URL，移除?后的所有参数
    const cleanedUrl = cleanUrl(url);
    const parseUrl = PARSE_APIS[currentApiIndex].url + encodeURIComponent(cleanedUrl);
    window.open(parseUrl, '_blank');
  };

  // 筛选历史记录 - 仅应用搜索筛选
  const filteredFavorites = favorites.filter(item => {
    return item.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.url.toLowerCase().includes(searchTerm.toLowerCase());
  });
  
  // 获取分类名称
  const getCategoryName = (categoryId: string | undefined) => {
    if (!categoryId) return null;
    const category = categories.find(c => c.id === categoryId);
    return category ? category : null;
  };

  // 开始编辑视频标题
  const startEditTitle = (timestamp: number, currentTitle: string) => {
    setEditingItem(timestamp);
    setTempTitle(currentTitle);
  };

  // 保存视频标题
  const saveTitle = (timestamp: number) => {
    if (tempTitle.trim()) {
      const newHistory = [...history];
      const index = newHistory.findIndex(item => item.timestamp === timestamp);
      if (index !== -1) {
        newHistory[index].title = tempTitle.trim();
        saveHistory(newHistory);
      }
    }
    setEditingItem(null);
  };

  // 取消编辑标题
  const cancelEditTitle = () => {
    setEditingItem(null);
  };

  // 开始编辑视频简介
  const startEditDescription = (timestamp: number, currentDescription: string = '') => {
    setEditingDesc(timestamp);
    setTempDescription(currentDescription);
  };

  // 保存视频简介
  const saveDescription = (timestamp: number) => {
    const newHistory = [...history];
    const index = newHistory.findIndex(item => item.timestamp === timestamp);
    if (index !== -1) {
      newHistory[index].description = tempDescription.trim() || undefined;
      saveHistory(newHistory);
    }
    setEditingDesc(null);
  };

  // 取消编辑简介
  const cancelEditDescription = () => {
    setEditingDesc(null);
  };

  // 处理拖拽开始
  const handleDragStart = (e: React.DragEvent, index: number) => {
    // 设置拖拽数据，指示拖拽的是哪个索引
    e.dataTransfer.setData('text/plain', index.toString());
    // 设置允许拖拽的效果
    e.dataTransfer.effectAllowed = 'move';
    setDragItemIndex(index);
  };

  // 处理拖拽结束
  const handleDragEnd = () => {
    setDragItemIndex(null);
    setDragOverItemIndex(null);
  };

  // 处理拖拽进入目标区域
  const handleDragEnter = (e: React.DragEvent) => {
    e.preventDefault();
    e.currentTarget.classList.add('bg-gray-50', 'dark:bg-gray-800');
  };

  // 处理拖拽离开目标区域
  const handleDragLeave = (e: React.DragEvent) => {
    e.currentTarget.classList.remove('bg-gray-50', 'dark:bg-gray-800');
  };

  // 处理拖拽在目标上方
  const handleDragOver = (e: React.DragEvent, index: number) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
    setDragOverItemIndex(index);
  };

  // 处理放置事件
  const handleDrop = (e: React.DragEvent, dropIndex: number) => {
    e.preventDefault();
    e.currentTarget.classList.remove('bg-gray-50', 'dark:bg-gray-800');
    
    const dragIndex = Number(e.dataTransfer.getData('text/plain'));
    
    // 如果拖放到相同位置，不进行任何操作
    if (dragIndex === dropIndex) return;
    
    // 获取当前项和目标项
    const draggedItem = filteredFavorites[dragIndex];
    const dropItem = filteredFavorites[dropIndex];
    
    if (!draggedItem || !dropItem) return;
    
    // 创建新的历史记录列表
    const newHistory = [...history];
    
    // 找到拖拽项和放置项在原始历史记录中的索引
    const dragHistoryIndex = newHistory.findIndex(item => item.timestamp === draggedItem.timestamp);
    const dropHistoryIndex = newHistory.findIndex(item => item.timestamp === dropItem.timestamp);
    
    if (dragHistoryIndex === -1 || dropHistoryIndex === -1) return;
    
    // 更新排序
    const draggedOrder = newHistory[dragHistoryIndex].order ?? 0;
    const dropOrder = newHistory[dropHistoryIndex].order ?? 0;
    
    // 更新所有受影响项目的顺序
    newHistory.forEach(item => {
      // 只处理收藏的项目
      if (!item.isFavorite) return;
      
      // 设置默认order如果不存在
      const currentOrder = item.order ?? 0;
      
      // 如果是向下拖动
      if (draggedOrder < dropOrder) {
        // 如果当前项在拖拽项和目标项之间，顺序减1
        if (currentOrder > draggedOrder && currentOrder <= dropOrder) {
          item.order = currentOrder - 1;
        } 
        // 如果是被拖拽的项目，移动到目标位置
        else if (item.timestamp === draggedItem.timestamp) {
          item.order = dropOrder;
        }
      } 
      // 如果是向上拖动
      else if (draggedOrder > dropOrder) {
        // 如果当前项在目标项和拖拽项之间，顺序加1
        if (currentOrder >= dropOrder && currentOrder < draggedOrder) {
          item.order = currentOrder + 1;
        }
        // 如果是被拖拽的项目，移动到目标位置
        else if (item.timestamp === draggedItem.timestamp) {
          item.order = dropOrder;
        }
      }
    });
    
    // 保存更新后的历史记录
    saveHistory(newHistory);
  };

  // 按照指定顺序排序收藏项
  const sortedFavorites = [...filteredFavorites].sort((a, b) => {
    // 如果两项都有order属性，按order排序
    if (a.order !== undefined && b.order !== undefined) {
      return a.order - b.order;
    }
    // 如果只有一项有order属性，有order的项排前面
    if (a.order !== undefined) return -1;
    if (b.order !== undefined) return 1;
    // 都没有order属性，按时间戳倒序排列
    return b.timestamp - a.timestamp;
  });

  return (
    <div className="flex h-full">
      {/* 侧边栏 */}
      <Sidebar 
        darkMode={darkMode} 
        username={username} 
        isOpen={sidebarOpen} 
        onToggle={() => setSidebarOpen(!sidebarOpen)} 
      />
      
      {/* 主内容区 */}
      <div className={`flex-1 md:ml-64 bg-white dark:bg-black min-h-screen text-black dark:text-white transition-all duration-300 ${
        sidebarOpen ? 'md:translate-x-0' : 'translate-x-0'
      }`}>
        {/* 顶部导航 */}
        <nav className="border-b border-gray-100 dark:border-gray-800">
          <div className="max-w-5xl mx-auto px-4 py-4 flex justify-between items-center">
            <div className="flex items-center">
              {/* 移动端汉堡菜单按钮 */}
              <button
                className="md:hidden mr-4 text-gray-600 dark:text-gray-400"
                onClick={() => setSidebarOpen(!sidebarOpen)}
                aria-label="打开菜单"
              >
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-6 h-6">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5" />
                </svg>
              </button>
              <h1 className="text-xl font-medium">我的收藏</h1>
            </div>
            <div className="text-sm text-gray-500 dark:text-gray-400">
              当前接口: {PARSE_APIS[currentApiIndex].name}
            </div>
          </div>
        </nav>

        <main className="max-w-5xl mx-auto px-4 py-8">
          {/* 搜索栏 */}
          <div className="mb-8">
            <div className="relative w-full sm:max-w-md">
              <input
                type="text"
                placeholder="搜索收藏..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full py-2 px-3 pr-10 border border-gray-200 dark:border-gray-800 rounded-lg bg-white dark:bg-black focus:outline-none focus:ring-1 focus:ring-gray-400 dark:focus:ring-gray-500"
              />
              <svg
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                viewBox="0 0 24 24"
                strokeWidth={1.5}
                stroke="currentColor"
                className="w-5 h-5 absolute right-3 top-1/2 -translate-y-1/2 text-gray-400"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z"
                />
              </svg>
            </div>
            {filteredFavorites.length > 1 && (
              <div className="mt-2 text-sm text-gray-600 dark:text-gray-300 flex items-center bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 p-2 rounded">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-4 h-4 mr-1 text-green-600 dark:text-green-400">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M11.25 11.25l.041-.02a.75.75 0 011.063.852l-.708 2.836a.75.75 0 001.063.853l.041-.021M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-9-3.75h.008v.008H12V8.25z" />
                </svg>
                <span>提示：<strong>仅拖动</strong>卡片左上角的<strong>拖动图标</strong>可调整收藏顺序</span>
              </div>
            )}
          </div>

          {/* 收藏列表 */}
          <div className="space-y-3">
            {filteredFavorites.length === 0 ? (
              <div className="py-12 text-center text-gray-400 dark:text-gray-500">
                {searchTerm ? '没有找到匹配的收藏' : '暂无收藏'}
              </div>
            ) : (
              sortedFavorites.map((item, index) => (
                <div 
                  key={item.timestamp}
                  onDragOver={(e) => handleDragOver(e, index)}
                  onDragEnter={handleDragEnter}
                  onDragLeave={handleDragLeave}
                  onDrop={(e) => handleDrop(e, index)}
                  className={`p-4 bg-white dark:bg-gray-900 border transition-all ${
                    dragItemIndex === index 
                      ? 'border-blue-400 dark:border-blue-600 opacity-50 scale-95' 
                      : dragOverItemIndex === index 
                        ? 'border-green-400 dark:border-green-600 bg-green-50 dark:bg-green-900/10' 
                        : 'border-gray-100 dark:border-gray-800'
                  } rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800`}
                >
                  <div className="flex flex-col md:flex-row md:justify-between md:items-start gap-3">
                    <div className="flex-1 min-w-0 relative">
                      {/* 操作按钮 - 仅在移动端显示为右下角水平排列 */}
                      <div className="md:hidden flex items-center space-x-2 text-gray-400 dark:text-gray-500 absolute bottom-0 right-0 pb-1">
                        <button
                          onClick={() => parseVideo(item.url)}
                          className="p-2 hover:text-blue-500 transition-colors"
                          title="解析视频"
                        >
                          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
                            <path strokeLinecap="round" strokeLinejoin="round" d="m15.75 10.5 4.72-4.72a.75.75 0 0 1 1.28.53v11.38a.75.75 0 0 1-1.28.53l-4.72-4.72M4.5 18.75h9a2.25 2.25 0 0 0 2.25-2.25v-9a2.25 2.25 0 0 0-2.25-2.25h-9A2.25 2.25 0 0 0 2.25 7.5v9a2.25 2.25 0 0 0 2.25 2.25Z" />
                          </svg>
                        </button>
                        <button
                          onClick={() => toggleFavorite(item)}
                          className="p-2 text-yellow-400 hover:text-yellow-500 transition-colors"
                          title="取消收藏"
                        >
                          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="w-5 h-5">
                            <path fillRule="evenodd" d="M10.788 3.21c.448-1.077 1.976-1.077 2.424 0l2.082 5.007 5.404.433c1.164.093 1.636 1.545.749 2.305l-4.117 3.527 1.257 5.273c.271 1.136-.964 2.033-1.96 1.425L12 18.354 7.373 21.18c-.996.608-2.231-.29-1.96-1.425l1.257-5.273-4.117-3.527c-.887-.76-.415-2.212.749-2.305l5.404-.433 2.082-5.006z" clipRule="evenodd" />
                          </svg>
                        </button>
                        <button 
                          onClick={() => removeFromHistory(item)}
                          className="p-2 hover:text-red-500 transition-colors"
                          title="删除记录"
                        >
                          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
                            <path strokeLinecap="round" strokeLinejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" />
                          </svg>
                        </button>
                      </div>

                      {/* 标题编辑区域 */}
                      {editingItem === item.timestamp ? (
                        <div className="flex flex-wrap items-center gap-2 mb-1">
                          <input
                            type="text"
                            value={tempTitle}
                            onChange={(e) => setTempTitle(e.target.value)}
                            className="px-2 py-1 text-base border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-black dark:text-white w-full md:w-64"
                            maxLength={50}
                            autoFocus
                          />
                          <div className="flex items-center">
                            <button
                              onClick={() => saveTitle(item.timestamp)}
                              className="p-1 text-green-600 dark:text-green-400"
                              title="保存"
                            >
                              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12.75l6 6 9-13.5" />
                              </svg>
                            </button>
                            <button
                              onClick={cancelEditTitle}
                              className="p-1 text-red-600 dark:text-red-400"
                              title="取消"
                            >
                              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                              </svg>
                            </button>
                          </div>
                        </div>
                      ) : (
                        <div className="flex items-center gap-2 mb-1 flex-wrap">
                          <div 
                            className="p-0.5 rounded hover:bg-gray-100 dark:hover:bg-gray-800 cursor-grab active:cursor-grabbing flex items-center justify-center shrink-0" 
                            title="拖拽此图标调整顺序"
                            draggable
                            onDragStart={(e) => handleDragStart(e, index)}
                            onDragEnd={handleDragEnd}
                          >
                            <svg 
                              xmlns="http://www.w3.org/2000/svg" 
                              fill="none" 
                              viewBox="0 0 24 24" 
                              strokeWidth={1.5} 
                              stroke="currentColor" 
                              className="w-5 h-5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                              aria-label="拖拽此图标调整顺序"
                            >
                              <title>拖拽此图标调整顺序</title>
                              <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 9h16.5m-16.5 6.75h16.5" />
                            </svg>
                          </div>
                          <p className="font-medium text-lg break-all">{item.title}</p>
                          <button
                            onClick={() => startEditTitle(item.timestamp, item.title)}
                            className="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 shrink-0"
                            title="修改名称"
                          >
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-4 h-4">
                              <path strokeLinecap="round" strokeLinejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10" />
                            </svg>
                          </button>
                          
                          {/* 桌面端操作按钮 */}
                          <div className="hidden md:flex ml-auto space-x-2 text-gray-400 dark:text-gray-500">
                            <button
                              onClick={() => parseVideo(item.url)}
                              className="p-2 hover:text-blue-500 transition-colors"
                              title="解析视频"
                            >
                              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
                                <path strokeLinecap="round" strokeLinejoin="round" d="m15.75 10.5 4.72-4.72a.75.75 0 0 1 1.28.53v11.38a.75.75 0 0 1-1.28.53l-4.72-4.72M4.5 18.75h9a2.25 2.25 0 0 0 2.25-2.25v-9a2.25 2.25 0 0 0-2.25-2.25h-9A2.25 2.25 0 0 0 2.25 7.5v9a2.25 2.25 0 0 0 2.25 2.25Z" />
                              </svg>
                            </button>
                            <button
                              onClick={() => toggleFavorite(item)}
                              className="p-2 text-yellow-400 hover:text-yellow-500 transition-colors"
                              title="取消收藏"
                            >
                              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="w-5 h-5">
                                <path fillRule="evenodd" d="M10.788 3.21c.448-1.077 1.976-1.077 2.424 0l2.082 5.007 5.404.433c1.164.093 1.636 1.545.749 2.305l-4.117 3.527 1.257 5.273c.271 1.136-.964 2.033-1.96 1.425L12 18.354 7.373 21.18c-.996.608-2.231-.29-1.96-1.425l1.257-5.273-4.117-3.527c-.887-.76-.415-2.212.749-2.305l5.404-.433 2.082-5.006z" clipRule="evenodd" />
                              </svg>
                            </button>
                            <button
                              onClick={() => removeFromHistory(item)}
                              className="p-2 hover:text-red-500 transition-colors"
                              title="删除记录"
                            >
                              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" />
                              </svg>
                            </button>
                          </div>
                        </div>
                      )}

                      {/* 分类标签 */}
                      {item.category ? (
                        <div className="flex items-center gap-2 mt-1">
                          {(() => {
                            const category = getCategoryName(item.category);
                            return category ? (
                              <div 
                                className="px-2 py-0.5 text-xs rounded-full text-white" 
                                style={{ backgroundColor: category.color }}
                              >
                                {category.name}
                              </div>
                            ) : null;
                          })()}
                          <button
                            onClick={() => setEditingCategoryIndex(item.timestamp)}
                            className="text-xs text-blue-500 hover:underline"
                          >
                            更改
                          </button>
                        </div>
                      ) : (
                        <button
                          onClick={() => setEditingCategoryIndex(item.timestamp)}
                          className="text-xs text-blue-500 hover:underline flex items-center mt-1"
                        >
                          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-4 h-4 mr-1">
                            <path strokeLinecap="round" strokeLinejoin="round" d="M9.568 3H5.25A2.25 2.25 0 0 0 3 5.25v4.318c0 .597.237 1.17.659 1.591l9.581 9.581c.699.699 1.78.872 2.607.33a18.095 18.095 0 0 0 5.223-5.223c.542-.827.369-1.908-.33-2.607L11.16 3.66A2.25 2.25 0 0 0 9.568 3Z" />
                            <path strokeLinecap="round" strokeLinejoin="round" d="M6 6h.008v.008H6V6Z" />
                          </svg>
                          添加分类
                        </button>
                      )}
                      
                      {/* 分类选择弹窗 */}
                      {editingCategoryIndex === item.timestamp && (
                        <div className="mt-2 p-2 bg-gray-50 dark:bg-gray-800 rounded border border-gray-200 dark:border-gray-700">
                          <div className="flex flex-wrap gap-2 mb-2">
                            {categories.map(category => (
                              <button
                                key={category.id}
                                onClick={() => updateItemCategory(item.timestamp, category.id)}
                                className="flex items-center gap-1 px-2 py-1 rounded text-xs hover:bg-gray-100 dark:hover:bg-gray-700"
                              >
                                <span 
                                  className="w-3 h-3 rounded-full" 
                                  style={{ backgroundColor: category.color }}
                                />
                                {category.name}
                              </button>
                            ))}
                            <button
                              onClick={() => updateItemCategory(item.timestamp, null)}
                              className="px-2 py-1 rounded text-xs hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-500"
                            >
                              无分类
                            </button>
                          </div>
                          <button
                            onClick={() => setEditingCategoryIndex(null)}
                            className="text-xs text-gray-500 hover:underline"
                          >
                            取消
                          </button>
                        </div>
                      )}
                      
                      <p className="text-sm text-gray-500 dark:text-gray-400 mb-2 break-all">
                        {item.url}
                      </p>
                      
                      {/* 视频简介 */}
                      {editingDesc === item.timestamp ? (
                        <div className="mb-2">
                          <textarea
                            value={tempDescription}
                            onChange={(e) => setTempDescription(e.target.value)}
                            className="w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-black dark:text-white"
                            placeholder="添加视频简介..."
                            rows={3}
                            maxLength={200}
                          />
                          <div className="flex items-center gap-2 mt-1">
                            <button
                              onClick={() => saveDescription(item.timestamp)}
                              className="p-1 text-xs text-green-600 dark:text-green-400 flex items-center"
                              title="保存"
                            >
                              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-4 h-4 mr-1">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12.75l6 6 9-13.5" />
                              </svg>
                              保存
                            </button>
                            <button
                              onClick={cancelEditDescription}
                              className="p-1 text-xs text-red-600 dark:text-red-400 flex items-center"
                              title="取消"
                            >
                              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-4 h-4 mr-1">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                              </svg>
                              取消
                            </button>
                          </div>
                        </div>
                      ) : (
                        <div className="mb-2">
                          {item.description ? (
                            <div className="text-sm text-gray-700 dark:text-gray-300 bg-gray-50 dark:bg-gray-850 p-2 rounded border border-gray-100 dark:border-gray-800 break-words">
                              {item.description}
                              <button
                                onClick={() => startEditDescription(item.timestamp, item.description)}
                                className="ml-2 text-xs text-blue-500 hover:underline"
                                title="编辑简介"
                              >
                                编辑
                              </button>
                            </div>
                          ) : (
                            <button
                              onClick={() => startEditDescription(item.timestamp)}
                              className="text-xs text-blue-500 hover:underline flex items-center"
                            >
                              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-4 h-4 mr-1">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M12 4.5v15m7.5-7.5h-15" />
                              </svg>
                              添加简介
                            </button>
                          )}
                        </div>
                      )}
                      
                      <p className="text-xs text-gray-400 dark:text-gray-500">
                        {new Date(item.timestamp).toLocaleString()}
                      </p>
                    </div>
                  </div>
                </div>
              ))
            )}
          </div>
        </main>

        {/* 页脚 */}
        <footer className="border-t border-gray-100 dark:border-gray-800 py-6 mt-12">
          <div className="max-w-5xl mx-auto px-4 text-center text-sm text-gray-500 dark:text-gray-400">
            <p>本工具仅用于学习和研究，请勿用于非法用途</p>
          </div>
        </footer>
      </div>
    </div>
  );
} 